package com.eci.context.context.feign;

import com.eci.common.asset.core.R;
import com.eci.common.asset.enums.ScodeEnum;
import com.eci.context.context.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class FeignInvocationHandler implements InvocationHandler {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 要代理的feign对象
     */
    private Object feignObject;

    /**
     * 当前appName
     */
    private String appName;

    public FeignInvocationHandler(Object feignObject, String appName) {
        this.feignObject = feignObject;
        this.appName = appName;
    }

    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        Object result;
        try {
            result = method.invoke(feignObject, objects);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("动态代理feign接口调用时，代理实例发生异常！");
        } catch (InvocationTargetException e) {
            log.error("feign调用异常", e);
            throw new BusinessException(appName + ScodeEnum.CALL_INNER_EXCEPTION.getCode(), ScodeEnum.CALL_INNER_EXCEPTION.getMessage());
        }
        R baseRsp;
        try {
            //强转为BaseRsp
            baseRsp = (R) result;
        } catch (Exception e) {
            throw new RuntimeException("feign接口调用异常，返回结果不是R！");
        }
        if (!ScodeEnum.SUCCESS.getCode().equals(baseRsp.getScode())) {
            //抛出我们的业务异常
            throw new BusinessException(baseRsp.getScode(), baseRsp.getMessage());
        }
        return result;
    }
}